import { defineStore } from "pinia";
import request from '@/api/request'
import { ElMessage } from "element-plus";
import router from '@/router'
import Layout from '@/views/Layout.vue'
import Bridge from '@/views/Bridge.vue'
let modules = import.meta.glob("../views/**/*.vue");

//推荐使用use名称开头
//state定义数据
//getter是用来做数据处理，如果不要处理数据，就不要定义
//action是用来定义函数，一般是异步函数
/**
 * 如果切换登录用户环境，funFangs改为不等于'dev'
 */
let useSys = defineStore("useSys", {
    state: () => {
        let user = undefined
        let treeMenus = undefined
        let menus = undefined
        let tabs = []
        let activeTab = "home"
        let token = '123'
        let LayoutValue = [] // header搜索页数据
        let runFangs = 'devs'
        return { user, menus, treeMenus, tabs, activeTab, token, LayoutValue, runFangs }
    },
    getters: {
        sessionUser() {
            if (!this.user) {
                let user = undefined;
                if (this.token != '123' || !this.token) {
                    // user = JSON.parse(decodeURIComponent(encodeURIComponent(window.atob(this.sessionToken.split('.')[1])))).claims;
                    // const jwtToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjbGFpbXMiOnsibG9naW5fbmFtZSI6IuS4iuS5i+WbnuWkueS4jeiHquS7oO+8iO+8iO2VnCwiLCJ0ZW5hbnRJZCI6OSwiaWQiOjEsImlkIjoxLCJ1c2VybmFtZSI6IuWbnuWkueS4jH0sImV4cCI6MTczMDkzNjA5OH0.iYdPloPogSIfdlhAaPiVnnlRg1LxS9TKsoXUDjFvdvQ';
                    const jwt = this.sessionToken
                    const parts = jwt.split('.');
                    const base64Payload = parts[1];
                    const payloadJson = JSON.parse(decodeURIComponent(escape(window.atob(base64Payload))));
                    user = payloadJson.claims
                } else {
                    user = {
                        login_name: '测试用户',
                        username: '测试用户',
                        tenantId: 9
                    }
                }
                this.user = user;
            }
            return this.user;
        },
        sessionToken() {
            if (this.runFangs == 'dev') {
                console.log('测试')
                if (!this.token) {
                    this.token = sessionStorage.getItem("token");
                }
            } else {
                console.log('运行')
                if (this.token == '123' || !this.token) {
                    this.token = sessionStorage.getItem("token");
                }
            }

            return this.token;
        },
        getLayoutValue() {
            if (this.LayoutValue.length == 0) {
                this.getMenusByUserId()
            }
            return this.LayoutValue;
        }
    },
    actions: { //async异步函数，如果函数中有远程请求的，那么这个方法就使用异步
        async login(username, password) {
            let result = false;
            //async 定义异步函数
            //await 等待异步函数执行完毕
            await request({
                url: "user/submitLogin",
                method: "post",
                params: {
                    username,
                    password
                }
            }).then(resp => {
                if (resp.code == 200) {
                    result = true;
                    sessionStorage.setItem("token", resp.data)
                }
            });
            return result;
        },
        async loadMenus() {
            //树形结构
            await request.get("menu/findMenuTree").then(resp => {
                this.treeMenus = resp.data
            });
            //没有树形结构
            await request.get("menu/findMenu").then(resp => {
                this.menus = resp.data
                resp.data.forEach(item => {
                    if (item.component) {
                        //新增属性
                        item.name = item.ename;
                        if (item.component == "Layout") {
                            //修改属性：component传入来的时候是string类型，
                            item.component = Layout
                            //item是路由对象{path,name,componet}
                            router.addRoute(item)
                        } else if (item.component == "Bridge") {
                            //修改属性
                            item.component = Bridge
                            //addRoute：一个是一个参数的方法，加载根路由
                            // addRoute(parentname,route)：第一个参数是父级的路由名称，后面是要添加的路由
                            router.addRoute(item.parentname, item)
                        } else {
                            //根据路径找到指定的vue文件，让item的component变成vue组件
                            item.component = modules[`../views/${item.component}.vue`]
                            router.addRoute(item.parentname, item)
                        }
                    }
                });
            });
            return true;
        },
        handleClickMenu(item) {
            //查找数组中是否已经存在了当前单击的菜单
            let flag = this.tabs.some(e => e.ename == item.ename);
            this.activeTab = item.ename;
            if (flag) return;
            //添加选项卡
            this.tabs.push(item);
        },
        // 权限查询
        async hasPermission(perm) {
            let m = this.menus.find(item => item.perm == perm)
            if (!m) {
                return Promise.reject("没有权限")
            }
            return Promise.resolve(m)
        },
        // 根据用户ID查询菜单列表(不包括顶级菜单)
        async getMenusByUserId() {
            await request.get("menu/getMenusByUserId").then(resp => {
                if (resp.code == 200) {
                    this.LayoutValue = resp.data
                }
            })
        },
        async quit() {
            let result = false;
            await request.get('quit').then(resp => {
                if (resp.code == 200) {
                    sessionStorage.removeItem('token');
                    sessionStorage.removeItem('routerName');
                    this.token = null;

                    this.treeMenus = undefined
                    this.user = undefined
                    result = true;
                }
            })
            return result;
        },
        async register(username, password) {
            let name = '';
            await request({
                url: 'user/getUserCountByUserName',
                method: 'get',
                params: {
                    username: username
                }
            }).then(async resp => {
                if (resp.data) {
                    await request({
                        url: 'user/register',
                        method: 'post',
                        data: {
                            username,
                            password
                        }
                    }).then(resp => {
                        if (resp.code == 200) {
                            name = resp.data;
                        }
                    })
                } else {
                    ElMessage.warning('该登录名已在本系统存在')
                }
            })
            return name;
        }
    }
});

export default useSys;